<template>
  <el-dialog :title="title" :visible.sync="visiable" width="60%" :before-close="handleClose" :close-on-click-modal="false">
    <el-form ref="formData" :model="formData" label-width="100px"  >
      <el-form-item label="标题:">
        <el-input v-model="formData.title" v-if="isEdit" placeholder="请输入标题" show-word-limit maxlength="50"></el-input>
        <el-input v-model="formData.title" v-if="!isEdit" readonly></el-input>
      </el-form-item>
      <el-form-item label="摘要:">
        <el-input type="textarea" v-model="formData.summary" v-if="isEdit" placeholder="请输入摘要" show-word-limit maxlength="300"></el-input>
        <el-input type="textarea" v-model="formData.summary" v-if="!isEdit" readonly></el-input>
      </el-form-item>
      <el-form-item label="作者:">
        <el-input v-model="formData.authorName"  readonly></el-input>
      </el-form-item>
      <el-form-item label="分类:">
        <el-select v-model="formData.categoryName" clearable filterable style="width:120px;" v-if="!isEdit" disabled >
          <el-option v-for="item in categoryList" :key="item.categoryId" :label="item.categoryName" :value="item.categoryName"></el-option>
        </el-select>
        <el-select v-model="checkedCategoryId" clearable filterable style="width:120px;" v-if="isEdit">
          <el-option v-for="item in categoryList"
                     :key="item.categoryId"
                     :label="item.categoryName"
                     :disabled="item.status === 2"
                     :value="item.categoryId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签:">
        <el-select v-model="formData.labelName" clearable filterable style="width:120px;" v-if="!isEdit" disabled >
          <el-option v-for="item in labelList" :key="item.labelId" :label="item.labelName" :value="item.labelName"></el-option>
        </el-select>
        <el-select v-model="checkedLabelId" clearable filterable style="width:120px;" v-if="isEdit">
          <el-option v-for="item in labelList"
                     :key="item.labelId"
                     :label="item.labelName"
                     :disabled="item.status === 2"
                     :value="item.labelId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="封面图">
        <img :src="formData.cover" style="width:178px; height:178px; display: block" v-if="!isEdit"/>
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadMainImg" v-if="isEdit">
          <img style="width:178px; height:178px; display: block" v-if="formData.cover" :src="formData.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="公开类型" prop="publicType">
        <el-radio-group v-model="formData.publicType" disabled v-if="!isEdit">
          <el-radio :label="1">仅自己可见</el-radio>
          <el-radio :label="2">组织内成员可见</el-radio>
          <el-radio :label="3">所有人可见</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.publicType" v-if="isEdit">
          <el-radio :label="1">仅自己可见</el-radio>
          <el-radio :label="2">组织内成员可见</el-radio>
          <el-radio :label="3">所有人可见</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="文章类型" prop="articleType">
        <el-radio-group v-model="formData.articleType" disabled v-if="!isEdit">
          <el-radio :label="1">原创</el-radio>
          <el-radio :label="2">转载</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.articleType" v-if="isEdit">
          <el-radio :label="1">原创</el-radio>
          <el-radio :label="2">转载</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="转载链接:"  v-if="formData.articleType === 2">
        <el-input v-model="formData.curationLink" v-if="isEdit"></el-input>
        <el-input v-model="formData.curationLink" v-if="!isEdit" readonly></el-input>
      </el-form-item>
      <el-form-item label="是否允许评论" prop="allowComment">
        <el-radio-group v-model="formData.allowComment" disabled v-if="!isEdit">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.allowComment" v-if="isEdit">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否允许下载" prop="allowDownload">
        <el-radio-group v-model="formData.allowDownload" disabled v-if="!isEdit">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.allowDownload" v-if="isEdit">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status" disabled v-if="!isEdit">
          <el-radio :label="1">草稿中</el-radio>
          <el-radio :label="2">待发布</el-radio>
          <el-radio :label="3">已发布</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.status" v-if="isEdit">
          <el-radio :label="1">草稿中</el-radio>
          <el-radio :label="2">待发布</el-radio>
          <el-radio :label="3">已发布</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="审批状态" prop="approveStatus">
        <el-radio-group v-model="formData.approveStatus" disabled v-if="!isEdit">
          <el-radio :label="1">待审批</el-radio>
          <el-radio :label="2">审批通过</el-radio>
          <el-radio :label="3">审批拒绝</el-radio>
        </el-radio-group>
        <el-radio-group v-model="formData.approveStatus" v-if="isEdit">
          <el-radio :label="1">待审批</el-radio>
          <el-radio :label="2">审批通过</el-radio>
          <el-radio :label="3">审批拒绝</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="审批人:">
        <el-input v-model="formData.approveUserName"  readonly></el-input>
      </el-form-item>
      <el-form-item label="审批时间:">
        <el-input v-model="formData.approveTime"  readonly></el-input>
      </el-form-item>
      <el-form-item label="审批留言:">
        <el-input v-model="formData.approveMessage"  readonly></el-input>
      </el-form-item>
      <el-form-item label="内容">
        <mavonEditor v-model="formData.mdContent" :editable="false" v-if="!isEdit"  />
        <mavonEditor ref="md" v-model="formData.mdContent" :editable="true" @imgAdd="uploadContentImg" v-if="isEdit" />
      </el-form-item>
      <el-form-item align="center" v-if="isEdit">
        <el-button type="primary" @click="submit('formData')" :loading="loading">确认</el-button>
        <el-button type="danger"  @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import { articleDetail, updateArticle } from "@/api/article";
import { getInfoByCreaterId } from "@/api/category";
import { uploadFile } from "@/api/file";
import { listByCategoryId } from "@/api/label";

export default {
  components:{
    mavonEditor, // 引入markdown编辑器
  },
  props:{
    id: null,  // 文章id
    isEdit:{  // 是否编辑页面
      type: Boolean,
      default: true
    },
    title:{
      type:String,
      default:''
    },
    visiable:{  // 弹出窗口
      type:Boolean,
      default:false
    },
    remoteClose: Function, //用于关闭窗口
  },

  data() {
    return {
      formData: {},
      categoryList: [],
      labelList: [],
      checkedCategoryId: '',
      checkedLabelId: '',
      categoryName: '',
      categoryId: '',
      valid: true,
      loading: false
    }
  },

  watch: {
    // 监听visiable的变化 将改变之后的值传入
    visiable(val) {
      if(val) {
        this.fetchArticleDetail();
        this.fetchCategory();
      }
    },

    checkedCategoryId (newId, oldId) {
      this.checkedCategoryId = newId;
      this.fetchLabelList();
    },

    checkedLabelId(newId, oldId) {
      this.checkedLabelId = newId;
    },
  },

  methods: {
    // 提交编辑
    submit() {
      this.loading = true;
      this.beforeSubmit()
      if (!this.valid) {
        this.valid = true
        return;
      }
      if (this.checkedCategoryId) {
        this.formData.categoryId = this.checkedCategoryId
      }
      if (this.checkedLabelId) {
        this.formData.labelId = this.checkedLabelId
      }
      updateArticle(this.formData).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '编辑成功',
            type: 'success',
            duration: 1500
          });
          this.handleClose();
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
        this.loading = false;
      })
    },

    // 获取所有的分类信息
    fetchCategory() {
      getInfoByCreaterId(this.formData.authorId).then(res => {
        if (res.code === 200) {
          this.categoryList = res.data;
        }
      })
    },

    // 获取标签列表
    fetchLabelList() {
      if (this.checkedCategoryId) {
        listByCategoryId(this.checkedCategoryId).then(res => {
          if (res.code === 200) {
            this.labelList = res.data;
          }
        })
      }
    },

    // 查询文章详情
    fetchArticleDetail() {
      articleDetail(this.id).then(res => {
        if (res.code === 200) {
          this.formData = res.data;
          this.formData.categoryName = this.formData.categoryName;
          this.checkedCategoryId = this.formData.categoryId;
          this.checkedLabelId = this.formData.labelId;
          getInfoByCreaterId(this.formData.authorId).then(res => {
            if (res.code === 200) {
              this.categoryList = res.data;
            }
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 3000
          });
          setTimeout(() => {
            this.handleClose();
          }, 1000)

        }
      })
    },

    uploadContentImg(pos,file) {
      const fd = new FormData();
      fd.append('file',file);
      uploadFile(fd).then(resp => {
        if(resp.code === 200){
          this.$refs.md.$img2Url(pos, resp.data);
        }
      })
    },

    // 上传图片 file 上传的图片对象
    uploadMainImg(file){
      const data = new FormData();
      data.append('file', file.file);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200){
          this.formData.cover = response.data;
        } else if (response.code === 403) {
          this.$notify.error({
            title: '错误',
            message: '您没有上传文件权限，请联系管理员',
            duration: 1500
          });
        } else {
          this.$notify.error({
            title: '错误',
            message: '系统异常，请稍后再试',
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    // 关闭窗口
    handleClose(){
      // 调用父组件的方法关闭窗口
      this.checkedCategoryId = '';
      this.categoryId = '';
      this.remoteClose();
    },

    beforeSubmit() {
      if (!this.formData.title) {
        this.$notify.error({
          title: '错误',
          message: '请输入标题',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.checkedCategoryId) {
        this.$notify.error({
          title: '错误',
          message: '请选择分类',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.formData.cover) {
        this.$notify.error({
          title: '错误',
          message: '请上传封面图',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.formData.publicType) {
        this.$notify.error({
          title: '错误',
          message: '请选择公开类型',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (this.formData.allowComment !== 0 && this.formData.allowComment !== 1) {
        this.$notify.error({
          title: '错误',
          message: '请选择是否允许评论',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (this.formData.allowDownload !== 0 && this.formData.allowDownload !== 1) {
        this.$notify.error({
          title: '错误',
          message: '请选择是否允许下载',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.formData.status) {
        this.$notify.error({
          title: '错误',
          message: '请选择状态',
          duration: 1500
        });
        this.valid = false
        return
      }

      if (!this.formData.htmlContent) {
        this.$notify.error({
          title: '错误',
          message: '请输入文章内容',
          duration: 1500
        });
        this.valid = false
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
